//
//  ProfileViewController.m
//  SEOBox
//
//  Created by Syd on 10-3-1.
//  Copyright 2010 MusicPeace.ORG. All rights reserved.
//

#import "ProfileViewController.h"
#import "LoadingView.h"
#import "ASIHTTPRequest.h"
#import "Project.h"
#import "NSString+Extras.h"


@implementation ProfileViewController
@synthesize project;
@synthesize managedObjectContext;
@synthesize projectTokens;

- (id)init {
    if (![super initWithNibName:@"ProfileView" bundle:nil]) return nil;
    return self;
}

- (void)dealloc {
    [project release];
    [managedObjectContext release];
    [projectTokens release];
    [super dealloc];
}

- (void)loadView {
    [super loadView];
    [self.view setAutoresizingMask:NSViewMaxXMargin|NSViewMaxYMargin|NSViewMinXMargin|NSViewMinYMargin|NSViewWidthSizable|NSViewHeightSizable];
    if (![project.html length]) {
        [self refresh:nil];
    }else {
        [self reload:nil];
    }
}

- (IBAction)refresh:(id)sender {
    LoadingView *progressView = [[LoadingView alloc] initWithFrame:[[self view] bounds]];
    [progressView startAnimating:nil];
    [[self view] addSubview:progressView];
    [progressView release];
    NSLog(@"URL: %@", project.url);
    NSURL *url = [NSURL URLWithString:project.url];
    ASIHTTPRequest *httpRequest = [ASIHTTPRequest requestWithURL:url];
    [httpRequest setDidFailSelector:@selector(failRefreshRequest:)];
    [httpRequest setDidFinishSelector:@selector(finishRefreshRequest:)];
    [httpRequest setDelegate:self];
    [httpRequest startAsynchronous];
}

- (void)failRefreshRequest:(ASIHTTPRequest *)aRequest {
    [self hideLoadingView];
    NSRunAlertPanel(@"Error", [NSString stringWithFormat:@"Can't fetch url: %@", project.url], @"OK", nil, nil);
}

- (void)finishRefreshRequest:(ASIHTTPRequest *)aRequest {
    project.html = [aRequest responseString];
    [self hideLoadingView];
    [self reload:nil];
}

- (IBAction)reload:(id)sender {
    LoadingView *progressView = [[LoadingView alloc] initWithFrame:[[self view] bounds]];
    [progressView startAnimating:nil];
    [[self view] addSubview:progressView];
    [progressView release];
    [self analysisPage:sender];
    [self hideLoadingView];
}

#pragma mark analysisPage
- (void)analysisPage:(id)sender {
    if (projectTokens) {
        [projectTokens release];
    }
    projectTokens = [[project.html flattenHTMLAndTrim:YES] stringTokens];
    NSLog(@"tokens: %@", [project.html flattenHTMLAndTrim:YES]);
}

#pragma mark helper methods

- (void)hideLoadingView {
    NSView *aView;
    for(aView in [self.view subviews])
    {
        if ([aView isKindOfClass:[LoadingView class]]) {
            [aView removeFromSuperview];
            break;
        }
    }
}
@end
